<?php
	mysql_connect("localhost", "root", "%Tg34fv1")or die("cannot connect"); 
	mysql_select_db("wordWaffle")or die("cannot select DB");
	$myKey = mysql_real_escape_string(stripslashes($_GET['sesskey']));
	$myCell = mysql_real_escape_string(stripslashes($_GET['cell']));
	$gameID = mysql_real_escape_string(stripslashes($_GET['gameID']));	
	
	//verify I'm in this game
	$result = mysql_query("SELECT * FROM players WHERE sesskey = $myKey");
	$count = mysql_num_rows($result);
	if ($count == 0)
	{
		echo "You are not a player in this game.  Please join a new game.";
		return;
	}
	//verify game is in progress
	$result = mysql_query("SELECT * FROM gameStatus WHERE gameID = $gameID");
	$row = mysql_fetch_assoc($result);
	if ($row['status'] != 1)
	{
		echo "Game is not currently in progress.  Please wait for a new game to begin.";
		return;
	}

	
	//verify my letter needs to be placed
	$result = mysql_query("SELECT * FROM lettersGuessed WHERE letter IS NOT NULL ORDER BY turnNumber DESC");
	$lettersChosenCount = mysql_num_rows($result);
	if ($lettersChosenCount > 0) //at least one letter has been chosen
	{
		$row = mysql_fetch_assoc($result);
		$thisTurn = $row['turnNumber'];
		$thisLetter = $row['letter'];
		$result = mysql_query("SELECT * FROM waffle WHERE sesskey='$myKey'");
		$lettersIvePlayed = mysql_num_rows($result);
		if ($lettersIvePlayed < $lettersChosenCount)
		{   //all right, everything checks out
			//now the only problem is if I've already used this cell
			$myX = substr($myCell,0,1);
			$myY = substr($myCell,1,1);
			$result = mysql_query("SELECT * FROM waffle WHERE sesskey='$myKey' AND x='$myX' AND y='$myY'");
			$count = mysql_num_rows($result);
			if ($row = mysql_fetch_assoc($result))
			{
				echo "You've already played here.";
				return;
			}
			else
			{
				$result=mysql_query("INSERT INTO waffle VALUES ('$myKey','$thisLetter','$thisTurn','$myX','$myY')");
				//Did I just place the last letter?
				$playerCount = mysql_num_rows(mysql_query("SELECT * FROM players WHERE readyToPlay=2 ORDER BY sesskey"));
				$waffleCount=mysql_num_rows(mysql_query("SELECT * FROM waffle"));
				if (($playerCount * 25) == $waffleCount) //yup
				{
					mysql_query("UPDATE gameStatus SET status=2 WHERE gameID=$gameID");
					$_GET = array();
					$_GET['sesskey'] = $myKey;
					include("score.php");
					mysql_query("UPDATE gameStatus SET status=3 WHERE gameID=$gameID");
				}
				echo $thisLetter;
				return;
			}
		}
		else
		{
			$result=mysql_query("SELECT * FROM lettersGuessed WHERE letter IS NULL ORDER BY turnNumber LIMIT 1");
			$turnKey = mysql_fetch_assoc($result);
			if ($turnKey['sesskey'] == $myKey)
				echo "Please choose a letter above!";
			else
				echo "Others are still placing $thisLetter.";
			return;
		}
	}
	else
	{
		echo "Please wait for the first letter to be chosen.";
		return;
	}
?>